<?php

namespace app\api\controller;
use Throwable;
use think\facade\Db;
use think\facade\Request;
use app\admin\model\Admin;
use app\admin\model\UserVip;
use app\admin\model\Order;
use app\admin\model\Device;
use app\admin\model\User as UserModel;
use app\api\service\userService;
use app\api\service\adminService;
use app\api\validate\Admin as AdminValidate;
use app\common\controller\Api;
class Dealer extends Api
{ 


    protected function initialize(): void
    {
	       parent::initialize(); // 调用父类初始化（可选）  
	       $this->params = $this->request->post("");
	       $admin_id = request()->adminId;
	       $admin = Admin::where("id",$admin_id)->where("status","enable")->find()->toArray();
	       if($admin){
               if(!in_array(6, $admin['group_arr'])){
               	  $this->error("无权限");
               }
            }else{
            	  $this->error("账号异常");
            }
	      
    }
    //数据报表
    function statics(){
    	 $agent_id = $this->params['agent_id'] ?? 0;
    	 $date = date("Y-m-d");
    	 $yesterday = date('Y-m-d', strtotime('-1 day'));
    	 $stime = strtotime($date." 00:00:00");
    	 $etime = strtotime($date." 23:59:59");

    	 $stime2 = strtotime($yesterday." 00:00:00");
    	 $etime2 = strtotime($yesterday." 23:59:59");

    	 $w['dealer_id'] = request()->adminId;
    	 if($agent_id){
    	 	 $w['agent_id'] = $agent_id;
    	 }
    	 $data['order_num'] = Order::where($w)->whereBetween("timestamp",[$stime,$etime])->count();
    	 $data['order_sum'] = Order::where($w)->whereBetween("timestamp",[$stime,$etime])->sum("money");
    	 $data['tui_sum'] = Order::where($w)->whereBetween("timestamp",[$stime,$etime])->whereIn("status",[7,8])->sum("money");
    	 $data['device_num'] = Device::where("market_id",request()->adminId)->whereBetween("timestamp",[$stime,$etime])->count();
    	 $data['profit'] = 299.00;

    	 //昨日
    	 $data['yesterday_order_num'] = Order::where($w)->whereBetween("timestamp",[$stime2,$etime2])->count();
    	 $data['yesterday_order_sum'] = Order::where($w)->whereBetween("timestamp",[$stime2,$etime2])->sum("money");
    	 $data['yesterday_tui_sum'] = Order::where($w)->whereBetween("timestamp",[$stime2,$etime2])->whereIn("status",[7,8])->sum("money");
    	 $data['yesterday_device_num'] = Device::where("market_id",request()->adminId)->whereBetween("timestamp",[$stime2,$etime2])->count();
    	 $data['yesterday_profit'] = 299.00;

    	 return json(['code'=>200,'data'=>$data]);
    }
    function agent(){
    	$res = Admin::where("market_id",request()->adminId)->field("username,nickname,id,remarks,mobile,profit_rate")->append(['device_num'])->select();
    	return json(['code'=>200,'data'=>$res,'msg'=>'ok']);
    }
    function addAgent(){
    	  $name = $this->params['name'] ?? '';
    	  $remarks = $this->params['remarks'] ?? '';
    	  $pwd = $this->params['pwd'] ?? '';
    	  $profit_rate = $this->params['profit_rate'] ?? '';
    	  $phone = $this->params['phone'] ?? '';
    	  $id = $this->params['id'] ?? 0;
    	  if($name == '' || $phone == ''){
    	  	   return json(['code'=>100,'msg'=>"名称、手机、分账比例必输填写"]);
    	  }
          $scene = 'add';
          if($id == 0){
                if(trim($pwd) == '' ){
                      return json(['code'=>100,'msg'=>"密码必输填写"]);
                }

                $data = [
                    'username'=>$phone,
                    'nickname'=>$name,
                    'mobile'=>$phone,
                    'password'=>hash_password($pwd),
                    'profit_rate'=>$profit_rate,
                    'remarks'=>$remarks,
                    'market_id'=>request()->adminId,
                    'access_token'=>generateRandomString(25),
                    'status'=>'enable'

               ];

          }else{
               $scene = 'edit';
               $data = [
                    'nickname'=>$name,
                    'mobile'=>$phone,
                    'profit_rate'=>$profit_rate,
                    'remarks'=>$remarks,
               ];

          }
 

    	    $validate = new AdminValidate();
	        try {
	            $validate->scene($scene)->check($data);
	        } catch (Throwable $e) {
	            $this->error($e->getMessage());
	        }

	        $model = new Admin();
	        $model->startTrans();
	        $result = false;
            try {
                if($id > 0){
                     $result = $model->where("id",$id)->update($data);
                     $result = true;
                }else{
                     $result = $model->save($data);
                     $r2 = Db::name('admin_group_access')->insert(['uid'=>$model->id,'group_id'=>7]);
                }
                
                $model->commit();
            } catch (Throwable $e) {
                $model->rollback();
                return json(['code'=>100,'msg'=>$e->getMessage()]);
            }
 			
			if($result){
            	 return json(['code'=>200,'msg'=>'ok']);
            }else{
            	 return json(['code'=>100,'msg'=>'失败']);
            }
    }

    //经销商查看下属所有订单

    function order(){
        $res = Order::where('dealer_id',request()->adminId)->order("oid desc")->select();
		return json(['code'=>100,'msg'=>'ok','data'=>$res]);

    }
    //今日订单统计
    function todayOrderCount()
    {
    	 $date = date("Y-m-d");
    	 $stime = strtotime($date." 00:00:00");
    	 $etime = strtotime($date." 23:59:59");
     	 $w[] = ['dealer_id','=',request()->adminId];
     	 $count['all'] = Order::where($w)->whereBetween('timestamp',[$stime,$etime])->count();
     	 $count['tui'] = Order::where($w)->whereBetween('timestamp',[$stime,$etime])->whereIn("status",[7,8])->count();
		 return json(['code'=>100,'msg'=>'ok','data'=>$count]);

    }
}